package com.dreamchaser.familydevice.util.system;

import java.util.HashMap;
import java.util.concurrent.locks.ReentrantLock;

/***
 *                    _ooOoo_
 *                   o8888888o
 *                   88" . "88
 *                   (| -_- |)
 *                    O\ = /O
 *                ____/`---'\____
 *              .   ' \\| |// `.
 *               / \\||| : |||// \
 *             / _||||| -:- |||||- \
 *               | | \\\ - /// | |
 *             | \_| ''\---/'' | |
 *              \ .-\__ `-` ___/-. /
 *           ___`. .' /--.--\ `. . __
 *        ."" '< `.___\_<|>_/___.' >'"".
 *       | | : `- \`.;`\ _ /`;.`/ - ` : | |
 *         \ \ `-. \_ __\ /__ _/ .-` / /
 * ======`-.____`-.___\_____/___.-`____.-'======
 *                    `=---='
 *
 * .............................................
 *          佛祖保佑             永无BUG
 *
 *
 * @author: SJie
 * @Date: 2020/3/11 19:28
 * @description:
 *
 */
public class LockManage {
    public static HashMap<String,ReentrantLock> operationLockMap = new HashMap(10);

    /**
     * 业务操作锁
     * @param userId
     * @return
     */
    public static ReentrantLock getOperationLock(Integer userId) {
        ReentrantLock lock = operationLockMap.get(userId.toString());
        if (lock == null) {
            synchronized (operationLockMap) {
                if (operationLockMap.get(userId.toString()) == null) {
                    ReentrantLock new_lock = new ReentrantLock();
                    operationLockMap.put(userId.toString(), new_lock);
                    return new_lock;
                } else {
                    return operationLockMap.get(userId.toString());
                }
            }
        }else{
            return lock;
        }


    }

    public static HashMap<String, ReentrantLock> moneyLock = new HashMap<>(10);
    /**
     * 账户相关锁
     * @param userId
     * @return
     */
    public static synchronized ReentrantLock getLock(Integer userId) {
        ReentrantLock lock = moneyLock.get(userId.toString());
        if (lock == null) {
            synchronized (moneyLock) {
                if (moneyLock.get(userId.toString()) == null) {
                    ReentrantLock new_lock = new ReentrantLock(true);
                    moneyLock.put(userId.toString(), new_lock);
                    return new_lock;
                } else {
                    return moneyLock.get(userId.toString());
                }
            }
        } else {
            return lock;
        }

    }
}
